"""日志引擎，将日志打印至指定文本框，不存在文件读取与生成"""
from threading import Thread
from queue import Queue
from core.constant import *
import tkinter as tk


class LogEngineModel:
    def __init__(self, file_manager, text_widget_dc, log_queue):
        self.file_manager = file_manager
        self.text_widget_dc = text_widget_dc
        self.log_queue: Queue = log_queue
        thread = Thread(target=self.emit_deal)
        thread.start()

    def emit(self, record, log_name: LogName):
        log_one = [record, log_name]
        self.log_queue.put(log_one)

    def emit_deal(self):
        while True:
            log_one = self.log_queue.get()
            if log_one[1] in [LogName.Operate_run_status, LogName.FileInfo]:
                msg = self.format_str(log_one[0])
                text_widget = self.text_widget_dc[log_one[1]]
                text_widget.delete("1.0", tk.END)
                # text_widget.insert("1.0", msg)
                # 配置标签样式
                text_widget.tag_config("red", foreground="red")
                for msg_o in msg.split('\n'):
                    if "名称:" in msg_o[:3]:
                        text_widget.insert(tk.END, f"{msg_o}")
                        line_start = text_widget.index("insert linestart")
                        line_end = text_widget.index("insert lineend")

                        # 应用标签到所有文本
                        text_widget.tag_add("red", line_start, line_end)
                        text_widget.insert(tk.END, f"\n")
                    else:
                        text_widget.insert(tk.END, msg_o+'\n')
            else:
                # print(log_one[0])
                msg = self.format_str(log_one[0])
                text_widget = self.text_widget_dc[log_one[1]]
                # text_widget.configure(state='normal')
                text_widget.insert(tk.END, msg + "\n")
                # text_widget.configure(state='disabled')
                text_widget.yview(tk.END)

    def clear(self, log_name: LogName):
        text_widget = self.text_widget_dc[log_name]
        text_widget.configure(state='normal')
        text_widget.delete(1.0, tk.END)
        text_widget.configure(state='disabled')

    def format_str(self, msg):
        from tools.framework import datetime_str
        # 将路径仅获取替换文本中出现的项目路径部分为...
        try:
            msg = msg.replace(self.file_manager.project_path, "\n...")
        except:
            pass
        msg = datetime_str() + msg
        return msg

